import 'package:flutter/material.dart';
import '../models/transaction.dart';
import '../services/database_service.dart';
import 'package:intl/intl.dart';
import 'transaction_detail_page.dart';

class AccountingPage extends StatefulWidget {
  const AccountingPage({super.key});

  @override
  State<AccountingPage> createState() => _AccountingPageState();
}

class _AccountingPageState extends State<AccountingPage> {
  late Future<List<Transaction>> _transactionsFuture;
  final _dateFormat = DateFormat('yyyy-MM-dd');
  final _numberFormat = NumberFormat('#,##0.00');
  DateTime _selectedMonth = DateTime.now();

  @override
  void initState() {
    super.initState();
    _loadTransactions();
  }

  void _loadTransactions() {
    _transactionsFuture = DatabaseService.instance.getTransactionsByMonth(_selectedMonth);
  }

  Future<void> _selectMonth() async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedMonth,
      firstDate: DateTime(2000),
      lastDate: DateTime.now(),
      initialEntryMode: DatePickerEntryMode.calendarOnly,
    );
    
    if (picked != null) {
      setState(() {
        _selectedMonth = DateTime(picked.year, picked.month);
        _loadTransactions();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<Transaction>>(
      future: _transactionsFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }

        if (snapshot.hasError) {
          return Center(child: Text('错误: ${snapshot.error}'));
        }

        final transactions = snapshot.data ?? [];
        final monthlyStats = _calculateMonthlyStats(transactions);

        return CustomScrollView(
          slivers: [
            SliverAppBar(
              floating: true,
              title: GestureDetector(
                onTap: _selectMonth,
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      '${_selectedMonth.year}年${_selectedMonth.month}月',
                    ),
                    const Icon(Icons.arrow_drop_down),
                  ],
                ),
              ),
            ),
            SliverToBoxAdapter(
              child: Card(
                margin: const EdgeInsets.all(16.0),
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          _buildStatItem('收入', monthlyStats.income, Colors.green),
                          _buildStatItem('支出', monthlyStats.expense, Colors.red),
                        ],
                      ),
                      const Divider(height: 32),
                      _buildStatItem(
                        '结余',
                        monthlyStats.income - monthlyStats.expense,
                        Colors.blue,
                      ),
                    ],
                  ),
                ),
              ),
            ),
            if (transactions.isEmpty)
              const SliverFillRemaining(
                child: Center(child: Text('暂无记录')),
              )
            else
              SliverList(
                delegate: SliverChildBuilderDelegate(
                  (context, index) {
                    final transaction = transactions[index];
                    final isExpense = transaction.type == TransactionType.expense;
                    
                    return ListTile(
                      leading: CircleAvatar(
                        backgroundColor: isExpense 
                            ? Colors.red.withOpacity(0.1)
                            : Colors.green.withOpacity(0.1),
                        child: Icon(
                          isExpense ? Icons.remove : Icons.add,
                          color: isExpense ? Colors.red : Colors.green,
                        ),
                      ),
                      title: Text(transaction.title),
                      subtitle: Text(
                        '${_dateFormat.format(transaction.date)} · ${transaction.category}',
                      ),
                      trailing: Text(
                        '${isExpense ? '-' : '+'}¥${_numberFormat.format(transaction.amount)}',
                        style: TextStyle(
                          color: isExpense ? Colors.red : Colors.green,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      onTap: () => _showTransactionDetail(transaction),
                    );
                  },
                  childCount: transactions.length,
                ),
              ),
          ],
        );
      },
    );
  }

  Widget _buildStatItem(String label, double amount, Color color) {
    return Column(
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ),
        ),
        const SizedBox(height: 4),
        Text(
          '¥${_numberFormat.format(amount)}',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
      ],
    );
  }

  Future<void> _showTransactionDetail(Transaction transaction) async {
    final result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => TransactionDetailPage(transaction: transaction),
      ),
    );

    if (result == true) {
      setState(() {
        _loadTransactions();
      });
    }
  }

  MonthlyStats _calculateMonthlyStats(List<Transaction> transactions) {
    var income = 0.0;
    var expense = 0.0;

    for (final transaction in transactions) {
      if (transaction.type == TransactionType.income) {
        income += transaction.amount;
      } else {
        expense += transaction.amount;
      }
    }

    return MonthlyStats(income: income, expense: expense);
  }
}

class MonthlyStats {
  final double income;
  final double expense;

  MonthlyStats({required this.income, required this.expense});
} 